package com.bwei.mypaot.utils;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;


import com.google.gson.Gson;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Administrator on 2017/1/10.
 * 使用单例模式来完成oKHttp拼接url和解析数据的封装
 */

public class OKHttpSingleTop {


    //声明对象
    CallbackM callbackM;
    //创建单例对象
    private static volatile OKHttpSingleTop oKHttpSingleTop;
    private Iterator<String> iterator;
    private final Gson gson;
    //获取主线程的handler
    private Handler handler;
    public OKHttpSingleTop() {
        handler=new Handler(Looper.getMainLooper());
        //初始化gson
        gson = new Gson();
    }
    public static OKHttpSingleTop getInstance(){
        if (null==oKHttpSingleTop){
            synchronized (OKHttpSingleTop.class){
                if (null==oKHttpSingleTop) {
                    oKHttpSingleTop=new OKHttpSingleTop();
                }

            }
        }

        return oKHttpSingleTop;
    }




    /**
     * get方法,拼接完整的url后调用方法使用okhttp进行解析数据
     *
     */
    public <T> void get(String url, Map<String,String> map, Class<T> Cls){
          int i=0;
        //便利包含参数的map集合
        iterator = map.keySet().iterator();
        while (iterator.hasNext()){
            String key =iterator.next();
            String value=map.get(key);
           if (i==0){
               //当第一次进入时直接拼接
               url+=key+"="+value;
           }else {
               //不是第一次进入时需要&连接参数
               url+="&"+key+"="+value;
           }
            i++;
        }
//        geturl(url,Cls);
//        Log.d("url",url);

    }


    //get请求
    public <T>  void geturl(String url, final Class<T> Cls){
        //创建OkHttpClient对象
        OkHttpClient okHttpClient=new OkHttpClient();
       //创建一个Request
        final Request request=new Request.Builder()
                .url(url)
                .build();
         //new call
        Call call=okHttpClient.newCall(request);
        //回调接口
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                //如果失败则调用接口里失败的方法
                if (null!=callbackM) {
                    callbackM.onFailure(request,e);
                }

            }
            @Override
            public void onResponse(Response response) throws IOException {
                String json= response.body().string();
                //通过调用getjson的方法来完成数据的解析
                getJson(json,Cls);

            }
        });

    }

    /**
     * GsoN解析
     */

    public  <T> void getJson(String json,Class<T> Cls){
       T t1=gson.fromJson(json,Cls);
       MainThread(t1);
    }

    //创建一个方法handler使用handler把数据发送到主线程来解析来进行解析
    public void MainThread(final Object response){
           handler.post(new Runnable() {
                       @Override
                       public void run() {
                           if (null!=callbackM) {
                               callbackM.onResponse(response);
                           }

               }
           });


    }

    //通过判断请求方式来调用方法拼接url
    public <T> void setUrl(String url,Map<String,String> map,Class<T> Cls,Methods methods){
        switch (methods){
            case GET:
                get(url,map,Cls);
                break;

            case POST:
                 Post(url,map,null);
                break;
        }
    }
    /*
    *  post 方法
    *  url 请求网络的地址
    *  map post 请求的参数
    *
    */

    public <T> void Post(String url, Map<String,String> map, final Class<T> Cls){


        //得到 client 对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //得到 body
        FormEncodingBuilder builder = new FormEncodingBuilder();
        //遍历
        Iterator<String> iterator = map.keySet().iterator();
        //加入到 builder 对象

        while (iterator.hasNext()){

            String key = iterator.next();
            String values = map.get(key);

            //加入到 builder 里面
            builder.add(key,values);

        }

        // 得到 request

        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();

        //得到 call

        final Call call = okHttpClient.newCall(request);


        //接口回调

        call.enqueue(new Callback() {


            @Override
            public void onFailure(Request request, IOException e) {

                if (null != callbackM) {
                    callbackM.onFailure(request, e);
                    Log.d("aaa","aapppp");
                }
            }

            @Override
            public void onResponse(Response response) throws IOException {

                String json = response.body().string();
                MainThread(json);
//                callbackM.onResponse(json);
                Log.d("aaa",json);
                getJson(json, Cls);
            }
        });


    }



    //观察者模式
    public interface  CallbackM{
        public void onFailure(Request request, IOException e);
        public void onResponse(Object response);
    }
    //创建方法以供调用
    public  void setCallbackM(CallbackM callbackM){
        this.callbackM=callbackM;

    }

    /**
     * 定义枚举类型
     * GET POST DOWN
     * 关键字段 enum
     *
     */
    public  enum Methods{
        GET,POST,DOWN
    }


}
